﻿//Copyright (c) 2010 Michael Ey

//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 


using System;
using Microsoft.DirectX.DirectInput;

namespace GameTrakXNA31
{
    /// <summary>
    /// This service handles initialization of the GameTrak, and allows polling of the GameTrak state.
    /// </summary>
    public class GameTrakService : IDisposable
    {
        /// <summary>
        /// The GUID of the GameTrak.
        /// </summary>
        private static Guid m_productGuid = new Guid("098214b7-0000-0000-0000-504944564944");

        /// <summary>
        /// The device reference.
        /// </summary>
        private Device m_gameTrakDevice = null;


        /// <summary>
        /// The current state of the GameTrak's axes and button.
        /// </summary>
        private static GameTrakState m_currentState;
        public static GameTrakState getState()
        {
            return m_currentState;
        }

        /// <summary>
        /// Gets the state by reference.
        /// </summary>
        /// <param name="currentState">An existing state instance to populate.</param>
        public void getState(out GameTrakState currentState)
        {
            currentState = m_currentState;
        }

        /// <summary>
        /// ctor.
        /// </summary>
        /// <param name="windowHandle">The handle of the window associated with this game.</param>
        public GameTrakService(IntPtr windowHandle)
        {

            //Enumerate devices and find the GameTrak based on it's Product Guid.
            foreach (DeviceInstance instance in Manager.GetDevices(
                DeviceClass.GameControl,
                EnumDevicesFlags.AttachedOnly))
            {
#if VERBOSE
                Console.WriteLine("Product Name: " + instance.ProductName);
                Console.WriteLine("Product Guid: " + instance.ProductGuid);
#endif
                //Once we find the right device, break out.
                if (instance.ProductGuid == m_productGuid)
                {
                    m_gameTrakDevice = new Device(instance.InstanceGuid);
                }
            }

            //Set axis modes.
            m_gameTrakDevice.Properties.AxisModeAbsolute = true;

            foreach (DeviceObjectInstance doi in m_gameTrakDevice.Objects)
            {
#if VERBOSE
                Console.WriteLine("Device Object Name: " + doi.Name + 
                    "Device ID: " + doi.ObjectId);
#endif
                if (doi.ObjectId == 1026 || //Y Rotation
                    doi.ObjectId == 770  || //X Rotation
                    doi.ObjectId == 258  || //Y Axis
                    doi.ObjectId == 2)      //X Axis
                {
                    m_gameTrakDevice.Properties.SetRange(ParameterHow.ById, doi.ObjectId, new InputRange(-1024, 1024));
                }

                if (doi.ObjectId == 1282 || //Z Rotation
                    doi.ObjectId == 514)   //Z Axis
                {
                    m_gameTrakDevice.Properties.SetRange(ParameterHow.ById, doi.ObjectId, new InputRange(0, 1024));
                }
            }

            //Set cooperative level.
            m_gameTrakDevice.SetCooperativeLevel(windowHandle, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

            //Acquire the device.
            m_gameTrakDevice.Acquire();
        }

        /// <summary>
        /// Disposes this GameTrak.
        /// </summary>
        public void Dispose()
        {
            if (m_gameTrakDevice != null)
            {
                m_gameTrakDevice.Unacquire();
            }
        }

        /// <summary>
        /// Polls the current state of the GameTrak.
        /// </summary>
        public void Poll()
        {
            m_gameTrakDevice.Poll();

            JoystickState state = m_gameTrakDevice.CurrentJoystickState;

            m_currentState.LeftCord = new Microsoft.Xna.Framework.Vector3(
                (float)(state.X) / 1024.0f,
                (float)(state.Y) / 1024.0f,
                1.0f - (float)(state.Z) / 1024.0f);

            m_currentState.RightCord = new Microsoft.Xna.Framework.Vector3(
                (float)(state.Rx) / 1024.0f,
                (float)(state.Ry) / 1024.0f,
                1.0f - (float)(state.Rz) / 1024.0f);

            byte[] buttons = state.GetButtons();
            if (buttons[0] == 0)
            {
                m_currentState.BigButton = Microsoft.Xna.Framework.Input.ButtonState.Released;
            }
            else
            {
                m_currentState.BigButton = Microsoft.Xna.Framework.Input.ButtonState.Pressed;
            }
        }
    }
}
